import json

from django.shortcuts import render, HttpResponse, redirect
import requests

# 请求的域名
Domain = "http://127.0.0.1:10000/"

NavArr = [
    {
        "id": 1,
        "title": "首页",
    },
    {
        "id": 2,
        "title": "新闻",
    },
]
HDomain = "https://www.hj87d29.top"


# 首页
def index(request, ):
    if request.method == 'GET':
        # 获取数据,默认1
        Page = request.GET.get("Page")
        BanKuaiId = request.GET.get("BanKuaiId")
        if Page is None:
            Page = 1
        elif BanKuaiId is None:
            BanKuaiId = 1
        
        params = {
            "Page": Page,
            "BanKuaiId": BanKuaiId
        }
        data = requests.get(url=Domain + f"haijiao/v1/card/list/", params=params).json()
        # 获取导航
        Result = {
            "Domain": Domain,
            "data": data
        }
        return render(request, '首页.html', context=Result)
    elif request.method == 'POST':
        pass
    else:
        return HttpResponse("不支持的请求方式", status=400)


# 新闻详情
def news_info(request):
    if request.method == 'GET':
        pid = request.GET.get("pid")
        if pid is None:
            return redirect('/yyty/index/')
            pass
        
        res = requests.get(url=Domain + "haijiao/v1/card/info/?Pid=" + pid).json()
        
        resurl = {
            "Domain": HDomain,
            "HDomain": HDomain + "/post/details?pid=" + pid,
            "data": res,
            "pid":pid
        }
        return render(request, '新闻详情.html', resurl)
    elif request.method == 'POST':
        res = requests.get(url=Domain + "haijiao/v1/Search/id/video/",params={
            "ImageID": request.POST.get("ImageID"),
            "TzID": request.POST.get("TzID"),
        }).json()
        return HttpResponse(json.dumps(res))


# 搜索
def news_search(request):
    if request.method == 'GET':
        result = {
            "SearchText": request.GET.get("SearchText"),
            "Domain": Domain,
        }
        return render(request, '搜索结果.html', result)
    elif request.method == 'POST':
        # 获取内容
        SearchText = request.POST.get("SearchText")
        Page = request.POST.get("Page")
        params = {
            "SearchText": SearchText,
            "Page": Page
        }
        data = requests.get(url=Domain + "haijiao/v1/SearchText/", params=params).json()
        result = {
            "data": data,
            "SearchText": SearchText,
            "length": len(data),
            "Domain": Domain,
        }
        return HttpResponse(json.dumps(result), status=200)
